#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.forms.models import ModelForm
from upload.models import Upload
import settings
from django import forms
import mimetypes
import pyclamd
from upload.formfields import ShortNameClearableFileInput


class UploadForm(ModelForm):
    """
    Form for Uploads
    """

    class Meta:
        model = Upload
        fields = ('upload', )
        widgets = {
            'upload': ShortNameClearableFileInput,
        }  

    def clean_upload(self):
        upload = self.cleaned_data['upload']
        
        """
        Make sure the file is not too big
        """
        if (not (settings.MAX_UPLOAD_SIZE == 0)) and (upload.size > settings.MAX_UPLOAD_SIZE):
            raise forms.ValidationError('Datei zu groß')
            return
        
        mimetype, _ = mimetypes.guess_type(upload.name, False)

        if mimetype in settings.UPLOAD_BLACKLIST:
            raise forms.ValidationError('Verbotenes Format hochgeladen')
        
        """
        Make sure there is no virus uploaded
        """
        if settings.ANTI_VIRUS:
            pyclamd.init_unix_socket(settings.CLAMD_PATH)
            ret = pyclamd.scan_stream(upload.read())

            if not ret == None:
                raise forms.ValidationError('Virus erkannt')

        return upload
    
#class DocumentUploadForm(DocumentForm, UploadForm):
#    """
#    Form for adding a Document and an Upload at the same time
#    In this form there is NO test for duplicate documents since this would
#    lower usability. REMEMBER THIS IN THE VIEW!
#    """
#    
#    def clean_name(self):
#        return self.cleaned_data["name"]